package ck.mmd.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import ck.mmd.bean.Knowledge;
import ck.mmd.bean.News;
import ck.mmd.bean.Remark;
import ck.mmd.dao.KnowledgeDao;
import ck.mmd.dao.RemarkDao;
import ck.mmd.dao.UserDao;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class KnowledgeAction extends ActionSupport  implements SessionAware{
	
	private static final long serialVersionUID = 1L;
	private Knowledge Knowledge;
	HttpServletRequest request = ServletActionContext.getRequest();
	HttpServletResponse response = ServletActionContext.getResponse();
	KnowledgeDao knowdao = new KnowledgeDao();
	UserDao userdao = new UserDao();
	private RemarkDao remarkdao = new RemarkDao();
	
	public String execute(){
		ActionContext context = ActionContext.getContext();
		//获取所有的知识
		List<Knowledge> newslist = new ArrayList<Knowledge>();
		String type = "10002";  //类别为知识
		newslist = knowdao.findAllKnowledgeByType(type);
		if(newslist.size() <= 0){
			context.put("isnull", 0);
			context.put("msg", "没有发布了的宠物知识...");
		}else{
			Iterator<Knowledge> it =  newslist.iterator();
			List<Knowledge> list = new ArrayList<Knowledge>();
			while(it.hasNext()){
				Knowledge knowledge = it.next();
				knowledge.setUser(userdao.findUserById(knowledge.getUp_id()));
				list.add(knowledge);
			}
			context.put("isnull", 1);
			context.put("list", list);
		}
		return "success";
	}
	
	/**
	 * 获取知识详情
	 * @return 返回详情对象
	 */
	public String detail(){
		ActionContext context = ActionContext.getContext();
		String id = request.getParameter("key");
		Knowledge Knowledge = new Knowledge();
		Knowledge = knowdao.findKnowledgeById(id);
		if(Knowledge == null){
			context.put("isnull", 0);
			context.put("msg", "SORRY...知识已经被搬运走了...");
		}else{
			context.put("isnull", 1);
			Knowledge.setUser(userdao.findUserById(Knowledge.getUp_id()));
			
			//查询评论
			List<Remark> remarklist = new ArrayList<Remark>();
			remarklist = remarkdao.findRemarksByUId(Knowledge.getId());
			if(remarklist.size() <= 0){
				context.put("size","0");
			}else{
				Iterator<Remark> it =  remarklist.iterator();
				List<Remark> remarklistdemo = new ArrayList<Remark>();
				while(it.hasNext()){
					Remark remark = it.next();
					remark.setUser(userdao.findUserById(remark.getUser_id()));
					remarklistdemo.add(remark);
				}
				context.put("size","1");
				context.put("remarklist",remarklistdemo);
			}
			context.put("item", Knowledge);
		}
		return "detail";
	}
	
	public void setSession(Map<String, Object> arg0) {
		
	}
	
	public Knowledge getModel() {
		if(this.Knowledge == null){
			return this.Knowledge = new Knowledge();
		}
		return this.Knowledge;
	}
}
